package com.jlwl.houseservice.service.impl;

import com.jlwl.houseservice.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 文件服务实现类
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.upload.path:/upload}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:http://localhost:8080/upload}")
    private String urlPrefix;

    @Override
    public String uploadImage(MultipartFile file) throws Exception {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只能上传图片文件");
        }

        // 生成文件保存路径
        String savePath = generateSavePath();
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = StringUtils.getFilenameExtension(originalFilename);
        String filename = UUID.randomUUID().toString() + "." + extension;
        
        // 保存文件
        Path filePath = Paths.get(savePath, filename);
        try {
            Files.createDirectories(filePath.getParent());
            Files.copy(file.getInputStream(), filePath);
        } catch (IOException e) {
            throw new IOException("文件保存失败", e);
        }
        
        // 返回文件访问URL
        return generateFileUrl(savePath, filename);
    }

    @Override
    public List<String> uploadImages(List<MultipartFile> files) throws Exception {
        List<String> imageUrls = new ArrayList<>();
        
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String imageUrl = uploadImage(file);
                imageUrls.add(imageUrl);
            }
        }
        
        return imageUrls;
    }
    
    /**
     * 生成文件保存路径
     * @return 保存路径
     */
    private String generateSavePath() {
        // 按日期生成目录结构
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return uploadPath + File.separator + datePath;
    }
    
    /**
     * 生成文件访问URL
     * @param savePath 保存路径
     * @param filename 文件名
     * @return 文件访问URL
     */
    private String generateFileUrl(String savePath, String filename) {
        String relativePath = savePath.substring(uploadPath.length());
        relativePath = relativePath.replace(File.separator, "/");
        
        if (!relativePath.startsWith("/")) {
            relativePath = "/" + relativePath;
        }
        
        return urlPrefix + relativePath + "/" + filename;
    }
} 